package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) throws Exception {
        //获取文件名称
        String filename = file.getOriginalFilename();
        //文件名称非空判断
        if (StringUtils.isEmpty(filename)) {
            throw new RuntimeException("文件名不能为空");
        }
        //文件类型
        String ext = file.getContentType();
        //文件长度
        long size = file.getSize();
        //文件内容
        byte[] context = file.getBytes();
        DtsStorage storage = storageService.add(filename, ext, size, context);
        return ResponseUtil.ok(storage);
    }
//http://localhost:8083/admin/storage/list?page=1&limit=20&sort=add_time&order=desc
    /**
     * 查询列表
     * @param page  当前页
     * @param limit 每页查询条数
     * @param sort  排序字段名
     * @param order 排序方式
     * @param key   根据key查询
     * @param name  根据名字查询
     * @return
     */
    @GetMapping("/list")
    public Object list(Integer page, Integer limit, String sort,
                       String order, String key, String name) {
        IPage<DtsStorage> storageIPage = storageService.queryByPage(page,
                limit, sort, order, key, name);
       //查询到的总条数
        long total = storageIPage.getTotal();
        //当前页的数据
        List<DtsStorage> records = storageIPage.getRecords();

        //封装
        Map<String, Object> map = new HashMap<>();

        map.put("total",total);
        map.put("items",records);
        return ResponseUtil.ok(map);
    }
}
